package com.swordxu.yim.server.packet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.swordxu.yim.server.packet.base.DefaultHeader;
import com.swordxu.yim.server.packet.base.Header;
import com.swordxu.yim.server.packet.base.Packet;
import com.swordxu.yim.server.utils.ProtocolConstant;
import org.apache.log4j.Logger;

/**
 * 请求/返回登录消息服务器 数据包
 * Created by 徐晓明 on 2015/1/6.
 */
public class MsgServerPacket extends Packet {
    private Logger logger = Logger.getLogger(MsgServerPacket.class);

    @Override
    public String encode() {
        Header header = mResponse.getHeader();
        PacketResponse res = (PacketResponse) mResponse;
        JSONObject jo = new JSONObject();
        jo.put("header", header);
//        JSONObject body = new JSONObject();
//        body.put("result", res.entity.result);
//        body.put("ip1", res.entity.ip1);
//        body.put("ip2", res.entity.ip2);
        jo.put("body", JSON.toJSON(res.entity));

        return jo.toJSONString();
    }

    @Override
    public void decode(String buffer) {
        PacketRequest rq = new PacketRequest();
        Header header = new Header();
        JSONObject jo = JSON.parseObject(buffer);
        header = jo.getObject("header", Header.class);
        rq.setHeader(header);
        rq.entity = jo.getObject("body", rq.entity.getClass());
        this.mRequest = rq;
    }

    public static class PacketRequest extends Request {
        public static class Entity {
            public int userType;
        }
        public Entity entity = new Entity();
    }

    public static class PacketResponse extends Response {
        public static class Entity {
            public int result;
            public String ip1;
            public String ip2;
            public short port;
        }

        public Entity entity;

        public PacketResponse(Entity entity) {
            this.entity = entity;
            Header header = new DefaultHeader(ProtocolConstant.SID_LOGIN, ProtocolConstant.CID_LOGIN_RES_MSGSERVER);
            setHeader(header);
        }
    }
}
